<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author ThinkGem
-->
<template>
  <ATableSummary fixed>
    <!-- 当页合计行 -->
    <ATableSummaryRow>
      <!-- 为 row-selection 添加空的 summary cell -->
      <ATableSummaryCell
        v-if="hasRowSelection"
        :index="0"
        :style="{ textAlign: 'center', fontWeight: 'bold' }"
      >
        <!-- 选择列的 summary cell，通常为空 -->
      </ATableSummaryCell>
      <ATableSummaryCell
        v-for="(item, index) in summaryData"
        :key="index"
        :index="hasRowSelection ? index + 1 : index"
        :style="{ textAlign: item.align, fontWeight: 'bold' }"
      >
        {{ item.summaryValue }}
      </ATableSummaryCell>
    </ATableSummaryRow>
    
    <!-- 总计行 -->
    <ATableSummaryRow v-if="showTotalSummary">
      <!-- 为 row-selection 添加空的 summary cell -->
      <ATableSummaryCell
        v-if="hasRowSelection"
        :index="0"
        :style="{ textAlign: 'center', fontWeight: 'bold' }"
      >
        <!-- 选择列的 summary cell，通常为空 -->
      </ATableSummaryCell>
      <ATableSummaryCell
        v-for="(item, index) in summaryData"
        :key="index"
        :index="hasRowSelection ? index + 1 : index"
        :style="{ textAlign: item.align, fontWeight: 'bold', fixed: item.fixed }"
      >
        {{ item.summaryTotalValue }}
      </ATableSummaryCell>
    </ATableSummaryRow>
  </ATableSummary>
</template>

<script lang="ts">
import { defineComponent, computed, ref, onMounted, onUnmounted, type PropType } from 'vue';
import { TableSummary, TableSummaryCell, TableSummaryRow } from 'ant-design-vue';
import type { BasicColumn } from '../types/table';
import { isArray } from '/@/utils/is';

export default defineComponent({
  name: 'TableCustomSummary',
  components: {
    ATableSummary: TableSummary,
    ATableSummaryCell: TableSummaryCell,
    ATableSummaryRow: TableSummaryRow,
  },
  props: {
    // 表格数据
    tableData: {
      type: Array,
      required: true,
      default: () => [],
    },
    // 列配置
    columns: {
      type: Array as PropType<BasicColumn[]>,
      required: true,
      default: () => [],
    },
    // 是否有行选择
    hasRowSelection: {
      type: Boolean,
      default: false,
    },
    // 是否显示总计行
    showTotalSummary: {
      type: Boolean,
      default: false,
    },
    // 其他数据（用于总计）
    otherData: {
      type: Object,
      default: () => ({}),
    },
    // 合计标签显示的列索引
    summaryLabelColumnIndex: {
      type: Number,
      default: 1,
    },
    // 当页合计标签
    summaryLabel: {
      type: String,
      default: '当页合计',
    },
    // 总计标签
    totalLabel: {
      type: String,
      default: '总计',
    },
    // 刷新触发器，用于强制重新计算合计
    refreshTrigger: {
      type: Number,
      default: 0,
    },
  },
  setup(props) {
    // 创建一个响应式的刷新计数器
    const refreshCounter = ref(0);

    // 定时器引用
    let refreshTimer: NodeJS.Timeout | null = null;

    // 启动定时刷新
    onMounted(() => {
      // 每500ms刷新一次合计，实现实时更新
      refreshTimer = setInterval(() => {
        refreshCounter.value++;
      }, 500);
    });

    // 清理定时器
    onUnmounted(() => {
      if (refreshTimer) {
        clearInterval(refreshTimer);
        refreshTimer = null;
      }
    });
    // 计算汇总数据
    const summaryData = computed(() => {
      const { tableData, columns, otherData, summaryLabelColumnIndex, summaryLabel, totalLabel, refreshTrigger } = props;

      // 触发刷新计数器，确保响应式更新
      refreshCounter.value;
      refreshTrigger;
      
      if (!tableData || tableData.length === 0) {
        return [];
      }

      const processedColumns = [...columns];

      // 处理每一列的汇总
      processedColumns.forEach((column, columnIndex) => {
        // 设置合计标签
        if (columnIndex === summaryLabelColumnIndex) {
          column.summaryValue = summaryLabel;
          column.summaryTotalValue = totalLabel;
        } else {
          // 处理需要汇总的列
          if (column.showSummary) {
            const summaryValue = tableData.reduce((pre, cur) => {
              const value = getColumnValue(cur, column.dataIndex);
              if (value === undefined || value === null || value === '') {
                return pre;
              }
              const numValue = Number(value);
              if (isNaN(numValue)) {
                return pre;
              }
              return pre + numValue;
            }, 0);

            // 格式化当页汇总值
            if (typeof summaryValue === 'number' && !isNaN(summaryValue)) {
              if (column.dataIndex === 'fweight') {
                column.summaryValue = summaryValue.toFixed(2);
              } else {
                column.summaryValue = summaryValue.toFixed(0);
              }
            } else {
              column.summaryValue = '';
            }

            // 处理总计汇总
            if (
              column.showTotalSummary &&
              otherData &&
              otherData[column.dataIndex] !== undefined
            ) {
              const totalValue = otherData[column.dataIndex];
              if (typeof totalValue === 'number' && !isNaN(totalValue)) {
                if (column.dataIndex === 'fweight') {
                  column.summaryTotalValue = totalValue.toFixed(2);
                } else {
                  column.summaryTotalValue = totalValue;
                }
              } else {
                column.summaryTotalValue = '';
              }
            } else {
              column.summaryTotalValue = '';
            }
          } else {
            column.summaryValue = '';
            column.summaryTotalValue = '';
          }
        }
      });

      return processedColumns;
    });

    // 获取列值的辅助函数
    function getColumnValue(record: Recordable, dataIndex: string | string[]) {
      if (isArray(dataIndex)) {
        return dataIndex.reduce((pre, cur) => {
          if (pre && pre[cur] !== undefined) return pre[cur];
          return '';
        }, record);
      }

      // 优先从 editValueRefs 中获取实时编辑的值
      if (record.editValueRefs && record.editValueRefs[dataIndex]) {
        const editValueRef = record.editValueRefs[dataIndex];
        // 如果是 ref 对象，获取其 value
        const editValue = editValueRef && typeof editValueRef === 'object' && 'value' in editValueRef
          ? editValueRef.value
          : editValueRef;

        // 如果编辑值存在且不为空，则使用编辑值
        if (editValue !== undefined && editValue !== null && editValue !== '') {
          return editValue;
        }
      }

      // 否则使用原始数据
      return record[dataIndex];
    }

    return {
      summaryData,
    };
  },
});
</script>
